<template>
  <div class="inner-page">
    <el-container>
      <el-header class="header">
        <div class="header-content">
          <div class="header-left">
            <el-button @click="$router.push('/dashboard')" icon="ArrowLeft" class="back-btn">
              返回
            </el-button>
          </div>
          <div class="header-center">
            <div class="page-title">
              <el-icon class="title-icon"><MoonNight /></el-icon>
              <h2>内心</h2>
            </div>
          </div>
          <div class="header-right">
            <div class="word-count">
              <div class="count-info">
                <span class="count-text">{{ wordCount }}字</span>
              </div>
            </div>
          </div>
        </div>
      </el-header>
      
      <el-main class="main">
        <el-card class="inner-card" @dblclick="handleContainerDoubleClick">
          <template #header>
            <div class="inner-header">
              <h3>内心历程</h3>
              <div class="inner-status">
                <el-tag v-if="isEditing" type="warning">编辑模式</el-tag>
                <el-tag v-else type="info">只读模式</el-tag>
                <span v-if="lastUpdateTime" class="update-time">
                  {{ lastUpdateTime }}
                </span>
              </div>
            </div>
          </template>
          
          <div class="inner-content">
            <el-input
              v-model="innerContent"
              type="textarea"
              placeholder="双击开始记录您的内心历程..."
              :readonly="!isEditing"
              @dblclick.stop="startEditing"
              resize="none"
              class="inner-textarea"
              ref="innerTextarea"
              @click.stop
              @input="adjustTextareaHeight"   
            />
          </div>
          
          <div class="inner-footer">
            <div class="edit-tip">
              <el-icon><InfoFilled /></el-icon>
              <span>双击文本框进入编辑模式，双击其他地方自动保存</span>
            </div>
            <div class="inner-description">
              <el-icon><MoonNight /></el-icon>
              <span>这里记录您的心路历程，是您内心世界的专属空间</span>
            </div>
          </div>
        </el-card>
      </el-main>
    </el-container>
    
    <!-- 悬浮主题切换按钮 -->

  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
// import axios from 'axios'
// 新写法（自动适配环境）
import request from '../utils/request'
import dayjs from 'dayjs'
import { InfoFilled, MoonNight } from '@element-plus/icons-vue'


const router = useRouter()
const innerContent = ref('')
const isEditing = ref(false)
const saving = ref(false)
const lastUpdateTime = ref('')
const innerTextarea = ref(null)

// 固定日期 2099-09-09
const currentDate = computed(() => {
  return dayjs('2099-09-09').toDate()
})

const formatDate = (date) => {
  return dayjs(date).format('YYYY年MM月DD日 dddd')
}

const wordCount = computed(() => {
  return innerContent.value ? innerContent.value.length : 0
})

// 格式化更新时间
const formatUpdateTime = (timestamp) => {
  if (!timestamp) return ''
  
  const now = new Date()
  const updateTime = new Date(timestamp)
  const timeDifference = Math.floor((now - updateTime) / 1000)
  
  if (timeDifference < 60) {
    return `${timeDifference} 秒前`
  } else if (timeDifference < 3600) {
    return `${Math.floor(timeDifference / 60)} 分钟前`
  } else if (timeDifference < 86400) {
    return `${Math.floor(timeDifference / 3600)} 小时前`
  } else if (timeDifference < 2592000) {
    return `${Math.floor(timeDifference / 86400)} 天前`
  } else {
    return dayjs(timestamp).format('YYYY年MM月DD日')
  }
}

// 新增：调整textarea高度以显示所有内容
const adjustTextareaHeight = () => {
  nextTick(() => {
    if (innerTextarea.value) {
      const textarea = innerTextarea.value.$el.querySelector('textarea')
      if (textarea) {
        // 先重置高度为auto以获取实际内容高度
        textarea.style.height = 'auto'
        // 设置高度为内容实际高度（加8px作为内边距补偿）
        textarea.style.height = `${textarea.scrollHeight + 8}px`
      }
    }
  })
}

const startEditing = () => {
  isEditing.value = true
  nextTick(() => {
    if (innerTextarea.value) {
      const textarea = innerTextarea.value.$el.querySelector('textarea')
      if (textarea) {
        textarea.focus()
        adjustTextareaHeight() // 进入编辑模式时调整高度
      }
    }
  })
}

const handleContainerDoubleClick = (event) => {
  const isTextareaClick = event.target.closest('.el-textarea') || 
                          event.target.classList.contains('el-textarea__inner')
  
  if (isTextareaClick) {
    return
  }
  
  if (isEditing.value) {
    isEditing.value = false
    saveInner()
  }
}

const loadInner = async () => {
  try {
    const dateString = '2099-09-09'
    const response = await  request.get(`/inner/${dateString}`)
    innerContent.value = response.data.inner.content || ''
    
    if (response.data.inner.updated_at) {
      lastUpdateTime.value = formatUpdateTime(response.data.inner.updated_at)
    } else {
      lastUpdateTime.value = ''
    }
    
    // 加载完成后调整高度
    adjustTextareaHeight()
  } catch (error) {
    console.error('加载内心历程失败:', error)
    ElMessage.error('加载内心历程失败')
  }
}

const saveInner = async () => {
  try {
    saving.value = true
    const dateString = '2099-09-09'
    await  request.post(`/inner/${dateString}`, {
      content: innerContent.value
    })
    ElMessage.success('保存成功')
    isEditing.value = false
    
    lastUpdateTime.value = formatUpdateTime(new Date())
  } catch (error) {
    console.error('保存内心历程失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

onMounted(() => {
  loadInner()
})
</script>

<style scoped>
/* 新增：修改卡片内容区域的内边距 */
::v-deep .el-card__body {
  padding: 5px; /* 根据需要调整数值，默认通常是15px左右 */
}

/* 可选：如果需要单独调整卡片头部的内边距 */
::v-deep .el-card__header {
  padding: 8px 20px; /* 头部上下内边距16px，左右24px */
}

.inner-page {
  min-height: 100vh;
  background-color: var(--bg-primary);
  
}

.header {
  /* background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%); */
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  position: relative;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-center {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 12px;
  background: rgba(255, 255, 255, 0.1);
  padding: 8px 16px;
  border-radius: 12px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.title-icon {
  font-size: 24px;
  color: #ffd700;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.2));
}

.page-title h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: white;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.date-navigation {
  display: flex;
  align-items: center;
  gap: 16px;
}

.current-date {
  font-size: 16px;
  font-weight: 600;
  min-width: 200px;
  text-align: center;
}

.main {
  padding: 20px;
}

.inner-card {
  max-width: 800px;
  margin: 0 auto;
}

.inner-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.inner-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #52c41a;
}

.inner-status {
  display: flex;
  align-items: center;
  gap: 12px;
}

.update-time {
  color: #909399;
  font-size: 12px;
}

.inner-content {
  margin-bottom: 20px;
  cursor: text;
}

.inner-textarea {
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.6;
  /* 移除固定高度限制 */
  height: auto !important;
  min-height: 320px; /* 设置最小高度，避免内容过少时过高 */
}

/* 隐藏滚动条 */
.inner-textarea ::v-deep .el-textarea__inner {
   min-height: 320px !important; /* 替换为你需要的最小高度（如 150px、200px） */
  overflow: hidden !important;
  resize: none !important;
}

.inner-footer {
  border-top: 1px solid #e0e0e0;
  padding-top: 16px;
}

.edit-tip {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #909399;
  font-size: 12px;
  margin-bottom: 8px;
}

.inner-description {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #52c41a;
  font-size: 12px;
  font-style: italic;
}

.status-tag {
  font-size: 14px;
}

.back-btn {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
  border-radius: 8px;
  font-weight: 500;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.word-count {
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.1);
  padding: 12px 20px;
  border-radius: 16px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
 
}

.word-count:hover {
  background: rgba(255, 255, 255, 0.15);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.count-info {
  display: flex;
  align-items: center;
  justify-content: center;
}

.count-text {
  font-size: 18px;
  font-weight: 600;
  /* color: #52c41a; */
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  font-family: 'Courier New', monospace;
}

@media (max-width: 768px) {
/* 仅 5+ App 环境生效（通过标记类精准控制） */
html.app-5plus .header {
  padding-top: var(--status-bar-height);
height: calc(55px + var(--status-bar-height));
}
   .header-content {
      /* 保持横向排列，不换行 */
      flex-direction: row; 
      padding: 10px 0;
      gap: 6px; /* 进一步缩小间距 */
        /* justify-content: center; */
    }

    .date-navigation {
      order: 0; /* 恢复默认顺序，不放在最上面 */
      gap: 6px;
    }

    /* 可选：如果按钮文字太长，可只保留图标（按需选择） */
    .header-content .el-button span {
      display: none; /* 隐藏按钮文字，只显示图标 */
     }
  /* .header-content {
    flex-direction: column;
    gap: 10px;
    padding: 10px 0;
  }
  
  .date-navigation {
    order: -1;
  } */
  
  .main {
    padding: 10px;
  }
  
  .current-date {
    min-width: 150px;
    font-size: 14px;
  }
  
  .inner-textarea {
    font-size: 13px;
      min-height: 320px; /* 设置最小高度，避免内容过少时过高 */
  }
    ::v-deep .el-textarea__inner {
      min-height: 320px !important; /* 替换为你需要的最小高度（如 150px、200px） */
    
    }
  .word-count {
    padding: 8px 16px;
  }
  
  .count-text {
    font-size: 16px;
  }
}
</style>
